package cn.rkylin.oms.salespromotion.rules.util.stretegy.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.order.domain.OrderSku;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.salespromotion.rules.domain.SalesPromotionConstrainGoods;
import cn.rkylin.oms.salespromotion.rules.util.stretegy.AbstractGiftCaculateStretegy;
import cn.rkylin.oms.salespromotion.rules.vo.SalesPromotionRuleVO;

public class OrderAmountCaculator extends AbstractGiftCaculateStretegy {
    @Override
    protected BigDecimal getCaculateNum(SalesPromotionRuleVO ruleVO, OrderVO order) {
        BigDecimal returnValue = new BigDecimal(0);
        JSONObject jsonObject = JSONObject.parseObject(ruleVO.getPresentCaculateRule());
        JSONObject jsonRuleItem = (JSONObject)jsonObject.getJSONArray("segments").get(0);
        String purchaseType = jsonObject.getString("purchaseType");
        if("anyGoods".equals(purchaseType)) {
            // 计算所有商品的件数
            returnValue = getAmount(order);
        }else {
            // 计算所有限制商品的件数
            returnValue = getConstrainSkuAmount(ruleVO,order);
        }
        return returnValue;
    }
    
    /**
     * getPieces:计算订单商品的总金额. <br/>
     *
     * @author zhanghao
     * @param order
     * @return
     */
    private BigDecimal getAmount(OrderVO order) {
        BigDecimal count = new BigDecimal(0);
        List<OrderSku> orderGoodsList = order.getSysOrderGoodsList();
        for (OrderSku orderSku : orderGoodsList) {
            count = count.add(orderSku.getDivideOrderFee());    // 计算实际支付金额
        }
        return count;
    }
    
    /**
     * getConstrainSkuPieces:计算订单商品中限制商品的总金额. <br/>
     *
     * @author zhanghao
     * @param ruleVO
     * @param order
     * @return
     */
    private BigDecimal getConstrainSkuAmount(SalesPromotionRuleVO ruleVO, OrderVO order) {
        BigDecimal count = new BigDecimal(0);
        List<OrderSku> orderGoodsList = order.getSysOrderGoodsList();
        List<SalesPromotionConstrainGoods> constrainGoodsList = ruleVO.getConstrainGoodsList();
        ArrayList<String> constraingoodsSkuCodeArray = new ArrayList<String>();
        for (SalesPromotionConstrainGoods salesPromotionConstrainGoods : constrainGoodsList) {
            constraingoodsSkuCodeArray.add(salesPromotionConstrainGoods.getRelGoodsSkuCode());
        }
        
        for (OrderSku orderSku : orderGoodsList) {
            // 如果订单商品不是赠品，且存在于限制商品列表中，则计算商品金额
            if(constraingoodsSkuCodeArray.contains(orderSku.getSkuCode())) {
                count = count.add(orderSku.getDivideOrderFee());
            }
        }
        return count;
    }

}
